package com.lh.api.interceptor;

import com.lh.api.annotation.Login;
import com.lh.api.config.MyConstants;
import com.lh.api.utils.JwtUtils;
import com.lh.common.entity.admin.User;
import com.lh.common.exception.RRException;
import com.lh.common.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }

        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if(StringUtils.isBlank(token)){
            token = request.getParameter(jwtUtils.getHeader());
        }

        //凭证为空并且有Login注解才提示不为空
        if(StringUtils.isBlank(token) && annotation != null){
            throw new RRException(HttpStatus.UNAUTHORIZED.value(),jwtUtils.getHeader() + "不能为空" );
        }

        if(StringUtils.isBlank(token)) {
            return true;
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){
            if(annotation != null) {
                throw new RRException(HttpStatus.UNAUTHORIZED.value(),jwtUtils.getHeader() + "失效，请重新登录");
            }

            logger.info("{}失效，请重新登录", jwtUtils.getHeader());
            return true;
        }
        //设置用户手机号到request里，后续根据用户手机号，获取用户信息
        request.setAttribute(MyConstants.USER_KEY,claims.getSubject());

        //设置用户数据到缓存
        String key = String.format(MyConstants.USER_INFO_CACHE,token);
        User userInfo = redisUtils.get(key,User.class);
        if(annotation != null && userInfo == null){
            throw new RRException(HttpStatus.UNAUTHORIZED.value(),jwtUtils.getHeader() + "失效,未找到用户，请重新登录");
        }
        request.setAttribute(MyConstants.USER_INFO_KEY, userInfo);

        return true;
    }
}
